.PHONY: default clean
include Config.make

HEAD_DIR_LIST := cxx corba
OS_DIR_LIST := boot memory
TEST_LIST := $(OBJ_PATH)/cxx/cxx.test.o $(OBJ_PATH)/corba/corba.test.o

SUBDIR_LIST := $(OS_DIR_LIST) $(HEAD_DIR_LIST) examples

default: subdir_rule $(OBJ_PATH)/c.img

$(OBJ_PATH)/c.img: $(OBJ_PATH)/ossym.list $(OBJ_PATH)/trampoline.bin $(OBJ_PATH)/bootmain.bin $(OBJ_PATH)/zeroimage.bin $(OBJ_PATH)/cxxfix.test.elf $(OBJ_PATH)/cxxpic.test.elf $(OBJ_PATH)/corbafix.test.elf $(OBJ_PATH)/corbapic.test.elf
	cd $(OBJ_PATH) && ./deployOS.sh

$(OBJ_PATH)/os.o: $(patsubst %, $(OBJ_PATH)/%, $(join $(OS_DIR_LIST), $(patsubst %, /%.package.o, $(OS_DIR_LIST)))) $(TEST_LIST)
	gcc -r -o $@ '-Wl,-(' $^ '-Wl,-)' -nostdlib -nostartfiles
$(OBJ_PATH)/head.o: $(patsubst %, $(OBJ_PATH)/%, $(join $(HEAD_DIR_LIST), $(patsubst %, /%.package.o, $(HEAD_DIR_LIST))))
	gcc -r -o $@ '-Wl,-(' $^ '-Wl,-)' -nostdlib -nostartfiles

$(OBJ_PATH)/os.prep: $(OBJ_PATH)/os.o $(OBJ_PATH)/head.o
	gcc -Wl,--eh-frame-hdr -Wl,-Map,$(OBJ_PATH)/os.map -Wl,-T,os.lds -o $@ $^ -nostdlib -nostartfiles
$(OBJ_PATH)/bootmain.bin: $(OBJ_PATH)/os.prep
	objcopy -O binary $< $@ -j bootmain
$(OBJ_PATH)/zeroimage.bin: $(OBJ_PATH)/os.prep
	objcopy -O binary $< $@ -j header -j zerotest -j text -j data -j ctors -j bss -j typeinfo -j .eh_frame -j cxxex -j .eh_frame_hdr
$(OBJ_PATH)/trampoline.bin: trampoline.S
	gcc -c -Iboot/ -o $(OBJ_PATH)/trampoline.o $<
	gcc -Wl,-Ttext,0x7c00 $(OBJ_PATH)/trampoline.o -o $@ -nostdlib -nostartfiles
	objcopy -O binary $(OBJ_PATH)/trampoline.o $@

$(OBJ_PATH)/cxxfix.test.elf $(OBJ_PATH)/cxxpic.test.elf: ELFO_BASENAME := cxx/cxx
$(OBJ_PATH)/cxxfix.test.elf: $(OBJ_PATH)/cxx/cxxfix.test.o
$(OBJ_PATH)/cxxpic.test.elf: $(OBJ_PATH)/cxx/cxxpic.test.o
$(OBJ_PATH)/corbafix.test.elf $(OBJ_PATH)/corbapic.test.elf: ELFO_BASENAME := corba/corba
$(OBJ_PATH)/corbafix.test.elf: $(OBJ_PATH)/corba/corbafix.test.o
$(OBJ_PATH)/corbapic.test.elf: $(OBJ_PATH)/corba/corbapic.test.o

# os export symbols.
$(OBJ_PATH)/os_symtab: $(OBJ_PATH)/os.prep
	objcopy -O binary $< $@ -j os_symtab
$(OBJ_PATH)/os_symtab_strings: $(OBJ_PATH)/os.prep
	objcopy -O binary $< $@ -j os_symtab_strings
$(OBJ_PATH)/ossym.list: $(OBJ_PATH)/os_symtab $(OBJ_PATH)/os_symtab_strings
	cd $(OBJ_PATH) && ./symbol.py

clean:
	(cd ../ && make clean prepare)
	find . -\( -name '*.ii' -or -name '*.s' -\) -exec rm -f {} \;

include Rules.make
